import { Console } from 'console';
import http = require('http');
export class RequestServer {

    constructor() { }
    /**
     * 调用第三方接口方法
     * @param url 
     * @param path 
     * @param port 
     * @param params 
     */
    public async requestApi(method: string, hostname: string, port: number, headers: any, path: string, params: any): Promise<any> {
        return new Promise((resolve, reject) => {
            const content = JSON.stringify(params),
                options = {
                    hostname: hostname,
                    port: port,
                    path: path,
                    method: method,
                    headers: headers
                };
            let result = null;

            let req = http.request(options, function (res) {
                //如果没有具体的返回值，判断接口状态和调用方式
                if (params.returnNull === true && method === 'delete') {
                    if (res.statusCode === 200) {
                        resolve('yes');
                    } else {
                        resolve('no')
                    }
                }
                res.setEncoding("utf8");
                res.on('data', function (chunk) {
                    result = JSON.parse(chunk.toString());
                });
                res.on('agentRemove', function (chunk) {
                    console.log('agentRemove', chunk);
                });
                res.on('timeout', function (chunk) {
                    console.log('timeout', chunk);
                });
                res.on('free', function (chunk) {
                    console.log('free', chunk);
                });
                res.on('error', function (e) {
                    result = e.message;
                });
                res.on('drain', function (chunk) {
                    console.log('drain', chunk);
                });
                res.on('end', function (chunk) {
                    if (!result) {
                        result = res.statusCode;
                    }
                    resolve(result);
                });
                res.on('close', function (chunk) {
                    //console.log('close', chunk);
                });
            });

            req.on('error', function (e) {
                reject(e.message);
            });
            req.write(content);
            req.end();
        });
    }


}
